<script lang="ts" setup>
import { loginAPI } from '@/apis/user'
import { setStorageToken } from '@/utils/storage'
import { showLoadingToast, showSuccessToast } from 'vant'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const username = ref('sujiehao')
const password = ref('123456')

// 获取 vue 路由器实例，需要写到 setup 顶级，不能嵌套到其他函数中
const router = useRouter()

const onSubmit = async () => {
  showLoadingToast({
    message: '登录中...', // 提示文案
    forbidClick: true, // 是否禁止背景点击，防止用户重复登录
  })
  // 调用登录接口
  const res = await loginAPI({
    username: username.value,
    password: password.value,
  })
  // 登录成功，将 token 持久化存储到本地存储
  // localStorage.setItem('interview-token', res.data.token)
  // 调用持久化工具的方法，将 token 存储到本地存储
  setStorageToken(res.data.token)
  // 成功轻提示
  showSuccessToast('登录成功')
  // 登录成功，跳转到首页
  router.push('/home')
}
</script>

<template>
  <div class="login-view">
    <!-- 导航栏 -->
    <van-nav-bar title="面经登录" />
    <van-form @submit="onSubmit">
      <van-field
        label="用户名"
        placeholder="请输入用户名"
        v-model="username"
        autocomplete="username"
        :rules="[
          { required: true, message: '请输入用户名' },
          { pattern: /^\w{5,}$/, message: '用户名至少包含5个字符' },
        ]"
      />
      <van-field
        label="密码"
        placeholder="请输入密码"
        type="password"
        v-model="password"
        autocomplete="current-password"
        :rules="[
          { required: true, message: '请输入密码' },
          { pattern: /^\w{6,}$/, message: '密码至少包含6个字符' },
        ]"
      />
      <!-- 登录按钮 -->
      <div class="form-button">
        <!-- native-type="submit" 标记为提交表单按钮 -->
        <van-button type="primary" block native-type="submit">登录</van-button>
      </div>
      <div class="tips">
        <router-link class="tips-link" to="/register">注册账号</router-link>
      </div>
    </van-form>
  </div>
</template>

<!-- lang="scss" 样式嵌套拥有更好的兼容性 -->
<!-- scoped 隔离组件的样式，避免样式冲突 -->
<style lang="scss" scoped>
.form-button {
  margin: 16px;
}

.tips {
  text-align: right;
  padding-right: 16px;

  .tips-link {
    font-size: 12px;
    color: #007aff;
  }
}
</style>
